import type { MenuProps } from "antd";
import { Dropdown } from "antd";
import { useEffect, useState } from "react";
import { deepClone, LockState, Pen } from "@meta2d/core";

interface Props {
  children: JSX.Element;
  disabled: boolean;
  open: boolean;
  closeMenu: () => void;
}

let itemsDefault: MenuProps["items"] = [
  { label: "置顶", key: "top" },
  { label: "置底", key: "bottom" },
  { label: "上一个图层", key: "up" },
  { label: "下一个图层", key: "down" },
  { type: "divider" },
  { key: "lock", label: "锁定" },
  { type: "divider" },
  { key: "Delete", label: "删除" },
  { type: "divider" },
  { key: "ctrlZ", label: "撤销" },
  { key: "ctrlY", label: "恢复" },
  { type: "divider" },
  { key: "ctrlX", label: "剪切" },
  { key: "ctrlC", label: "复制" },
  { key: "ctrlV", label: "粘贴" },
  // { type: "divider" },
  // { key: "saveAsCom", label: "保存为组件" },
];
function getPenPath(pen: Pen) {
  let newPen = deepClone(pen);
  Reflect.deleteProperty(newPen, "calculative");
  return newPen;
}
const ContextMenu = (props: Props) => {
  const [items, setItems] = useState<MenuProps["items"]>(itemsDefault);

  const onClick: MenuProps["onClick"] = ({ key }) => {
    let activePen = window.meta2d.store.active || [];
    let circulateSet = (fn: (pen: Pen) => void) => {
      activePen.forEach((pen) => {
        fn(pen);
      });
    };
    const saveAsComponents = () => {
      let activePen = window.meta2d.store.active || [];
      let comName = prompt("组件名称");
      if (comName == null) {
        return;
      }
      let myComponents = JSON.parse(
        localStorage.getItem("myComponents") || "[]",
      );
      myComponents = [
        ...myComponents,
        {
          name: comName,
          value: activePen.map((v) => getPenPath(v)),
        },
      ];
      localStorage.setItem("myComponents", JSON.stringify(myComponents));
    };
    switch (key) {
      case "lock":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.setValue({
              id: pen.id,
              locked: LockState.DisableMove,
            });
          });
        }
        break;
      case "unlock":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.setValue({
              id: pen.id,
              locked: LockState.None,
            });
          });
        }
        break;
      case "top":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.top(pen);
          });
        }
        break;
      case "bottom":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.bottom(pen);
          });
        }
        break;
      case "up":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.up(pen);
          });
        }
        break;
      case "down":
        if (activePen.length > 0) {
          circulateSet((pen: Pen) => {
            window.meta2d.down(pen);
          });
        }
        break;
      case "combine":
        window.meta2d.combine(activePen);
        break;
      case "combineToStatus":
        window.meta2d.combine(activePen, 0);
        break;
      case "cancelCombine":
        window.meta2d.uncombine(activePen[0]);
        break;
      case "ctrlZ":
        window.meta2d.undo();
        break;
      case "ctrlY":
        window.meta2d.redo();
        break;
      case "ctrlX":
        window.meta2d.cut();
        break;
      case "ctrlC":
        window.meta2d.copy();
        break;
      case "ctrlV":
        window.meta2d.paste();
        break;
      case "ctrlA":
        window.meta2d.activeAll();
        break;
      case "Delete":
        window.meta2d.delete();
        break;
      case "saveAsCom":
        saveAsComponents();
        break;
      default:
        break;
    }
    props.closeMenu();
  };
  const onOpenChange = () => {
    let activePen = window.meta2d.store.active || [];
    if (activePen.length > 0 && activePen[0].locked == undefined) {
      activePen[0].locked = LockState.None;
    }
    if (activePen.length <= 0) {
      setItems(() => [
        { label: "置顶", key: "top", disabled: true },
        { label: "置底", key: "bottom", disabled: true },
        { label: "上一个图层", key: "up", disabled: true },
        { label: "下一个图层", key: "down", disabled: true },
        { type: "divider" },
        { key: "lock", label: "锁定", disabled: true },
        { type: "divider" },
        { key: "Delete", label: "删除", disabled: true },
        { type: "divider" },
        { key: "ctrlZ", label: "撤销" },
        { key: "ctrlY", label: "恢复", disabled: true },
        { type: "divider" },
        { key: "ctrlX", label: "剪切", disabled: true },
        { key: "ctrlC", label: "复制", disabled: true },
        { key: "ctrlV", label: "粘贴" },
        // { type: "divider" },
        // { key: "saveAsCom", label: "保存为组件", disabled: true },
      ]);
    } else {
      let lockedItem =
        activePen[0].locked == LockState.None
          ? { key: "lock", label: "锁定" }
          : { key: "unlock", label: "解锁" };

      let newMenuItem: MenuProps["items"] = itemsDefault?.map((it) => {
        if (it?.key == "lock" || it?.key == "unlock") {
          return lockedItem;
        } else {
          return it;
        }
      });
      if (newMenuItem == undefined) return;
      let isCombine = activePen[0].children && activePen[0].children.length > 0;
      if (isCombine) {
        newMenuItem.splice(5, 0, { key: "cancelCombine", label: "取消组合" });
      }
      if (activePen.length == 1) {
        setItems(newMenuItem);
      } else {
        newMenuItem.splice(5, 0, { key: "combine", label: "组合" });
        newMenuItem.splice(6, 0, {
          key: "combineToStatus",
          label: "组合为状态",
        });
        setItems(newMenuItem);
      }
    }
  };
  useEffect(() => {
    window.oncontextmenu = function (_) {
      //取消默认的浏览器自带右键
      onOpenChange();
    };
  }, []);

  return (
    <Dropdown
      open={props.open}
      disabled={props.disabled}
      onOpenChange={onOpenChange}
      menu={{ items, onClick }}
      trigger={["contextMenu"]}
      destroyPopupOnHide
      overlayStyle={{
        width: 200,
      }}
    >
      {props.children}
    </Dropdown>
  );
};

export default ContextMenu;
